package chat

import (
	v1 "SmartLibrary/api/v1"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"github.com/spf13/viper"
	"net/url"
	"strings"
	"time"
)

type Chat struct {
	HostUrl   string
	AppID     string
	ApiSecret string
	ApiKey    string
}

func NewChat(conf *viper.Viper) *Chat {
	chat := &Chat{
		HostUrl:   conf.GetString("chat.host_url"),
		AppID:     conf.GetString("chat.app_id"),
		ApiSecret: conf.GetString("chat.api_secret"),
		ApiKey:    conf.GetString("chat.api_key"),
	}

	return chat
}

func (c *Chat) GenerateURL() string {
	ul, _ := url.Parse(c.HostUrl)

	//签名时间
	date := time.Now().UTC().Format(time.RFC1123)
	//参与签名的字段 host ,date, request-line
	signString := []string{"host: " + ul.Host, "date: " + date, "GET " + ul.Path + " HTTP/1.1"}
	//拼接签名字符串
	sign := strings.Join(signString, "\n")

	// 使用 hmac-sha256 算法结合 APISecret 对 tmp 签名
	h := hmac.New(sha256.New, []byte(c.ApiSecret))
	h.Write([]byte(sign))
	tpmSha := h.Sum(nil)
	signature := base64.StdEncoding.EncodeToString(tpmSha)

	//构建请求参数 此时不需要urlencoding
	authUrl := fmt.Sprintf("hmac username=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", c.ApiKey,
		"hmac-sha256", "host date request-line", signature)
	//将请求参数使用base64编码
	authorization := base64.StdEncoding.EncodeToString([]byte(authUrl))

	v := url.Values{}
	v.Add("authorization", authorization)
	v.Add("date", date)
	v.Add("host", ul.Host)

	return c.HostUrl + "?" + v.Encode()
}

func (c *Chat) GenerateParams(messages *[]v1.ChatConditions) map[string]interface{} {
	return map[string]interface{}{
		"header": map[string]interface{}{
			"app_id": c.AppID,
		},
		"parameter": map[string]interface{}{
			"chat": map[string]interface{}{
				"domain": "general",
			},
		},
		"payload": map[string]interface{}{
			"message": map[string]interface{}{
				"text": messages,
			},
		},
	}
}
